import json
import os
import re
import shutil

from common.utils.decorator import type_validate


class FileUtil:
    @staticmethod
    def mkdir(path):
        """ 先删除目录，再新建 """
        if os.path.exists(path):
            try:
                shutil.rmtree(path)
            except IOError:
                raise Exception(f'目录：{path}无法删除')
        os.mkdir(path)

    @staticmethod
    def get_files_dirs(path):
        files = [file for file in os.listdir(path) if os.path.isfile(file)]
        dirs = [file for file in os.listdir(path) if os.path.isdir(file)]
        return files, dirs


class CacheUtil:
    result = {}

    @classmethod
    def query(cls):
        return CacheUtil.result

    @classmethod
    @type_validate
    def save(cls, cache: dict):
        CacheUtil.result = cache
        return CacheUtil.result

    @classmethod
    @type_validate
    def update(cls, cache):
        CacheUtil.result.update(cache)
        return CacheUtil.result

    @classmethod
    @type_validate
    def delete(cls, cache):
        CacheUtil.result.pop(cache)
        return CacheUtil.result

    @classmethod
    def clear(cls):
        CacheUtil.result = {}
        return CacheUtil.result

    @classmethod
    def replace(cls, params, cache_key):
        """ 使用cache中key为cache_key的字典值，替换params中以${}开头的变量 """
        if not params:
            return
        cache = CacheUtil.result[cache_key]
        for k, v in params.items():
            matcher = re.match(r'^\${(.*)}$', str(v))
            if matcher:
                # 获取${}中间的变量名，并根据变量名找到cache中的变量值进行替换
                variable = matcher.groups()[0]
                params[k] = cache[variable]


if __name__ == '__main__':
    result = CacheUtil.save({'xiaoming': {'name': 'xiaoming', 'age': 18}})
    print(result)
    params = {'name': '${name}', 'age': '${age}'}
    CacheUtil.replace(params, 'xiaoming')
    print(params)

